//
//  CreditCardListViewController.m
//  NewPro
//
//  Created by RYX on 2019/6/10.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "CreditCardListViewController.h"
#import "NewHomeStore.h"
#import "CreditCardListCell.h"
#import "CreditCardDetailViewController.h"
#import "HomeList.h"
#import "RecommendModel.h"
#import "UINavigationBar+handle.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApi.h"
#import "CreditCardStore.h"
#import "CreditCardFooterView.h"
#import "CreditCardListHeaderView.h"

@interface CreditCardListViewController ()<UITableViewDelegate,UITableViewDataSource,CreditCardFooterViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (copy, nonatomic) NSArray *listArr;
@property (nonatomic,strong) UIView *bgView;
@property (nonatomic, strong) UIView *shareView;
@property (nonatomic, strong) CreditCardFooterView *footerView;
@property (nonatomic, strong) CreditCardListHeaderView *headerView;
@end

@implementation CreditCardListViewController

- (CreditCardListHeaderView *)headerView{
    
    if (!_headerView) {
        
        CGFloat scale = 0.752;
        _headerView = [[CreditCardListHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth * scale)];
        
    }
    return _headerView;
}

- (CreditCardFooterView *)footerView{
    
    if (!_footerView) {
        
        _footerView = [[CreditCardFooterView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 272)];
        _footerView.delegate = self;
    }
    return _footerView;
}

- (UIView *)bgView{
    
    if (!_bgView) {
        
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        [_bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didBgView)]];
    }
    
    return _bgView;
}

- (void)didBgView{
    
    MJWeakSelf
    [UIView animateWithDuration:0.2 animations:^{
        
        weakSelf.shareView.y = SCREEN_HEIGHT + 50;
        weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        
    } completion:^(BOOL finished) {
        
        [weakSelf.bgView removeFromSuperview];
    }];
    
}

- (UIView *)shareView{
    
    if (!_shareView) {
        
        _shareView = [[[NSBundle mainBundle] loadNibNamed:@"CreditCardShareView" owner:self options:nil] objectAtIndex:0];
        _shareView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 105);
        _shareView.y = SCREEN_HEIGHT + 50;
        
    }
    
    return _shareView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor clearColor] image:nil isOpaque:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.translucent = NO;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = self.footerView;
        _tableView.tableHeaderView = self.headerView;
        _tableView.backgroundColor= [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavBarWithTitle:@"热门推荐"];
    
    [self addRightBtn];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"F41458"];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    
    [self.view addSubview:self.shareView];
    
    [self loadData];
}

- (void)addRightBtn{
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //修改按钮向左偏移10 point
    [rightBtn setFrame:CGRectMake(10.0, 0.0, 44.0, 44.0)];
    [rightBtn addTarget:self action:@selector(onRightBtn:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"分享"] forState:UIControlStateNormal];
    //修改方法
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)];
    [view addSubview:rightBtn];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    
    self.navigationItem.rightBarButtonItem = rightItem;
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
}

- (void)onRightBtn:(UIButton *)sender{
    
    if (self.shareView.y >= ScreenHeight){
        
        [self.view insertSubview:self.bgView belowSubview:self.shareView];
        
        MJWeakSelf
        [UIView animateWithDuration:0.7 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:0 animations:^{
            
            weakSelf.shareView.y = SCREEN_HEIGHT - 105;
            weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
            
        } completion:nil];
        
    }else{
        
        
        [self didBgView];
        
    }
}

- (void)loadData{
    
    MJWeakSelf
    NewHomeStore *store = [[NewHomeStore alloc] init];
    [store getRecommendTwoPageWithId:[HomeList sharedInstance].recommendModel.uid Success:^(NSArray *arr) {
        
        weakSelf.listArr = arr;
        [weakSelf.tableView reloadData];
                
    } Failure:^(NSError *error) {
        
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return (ScreenWidth - 28) * 0.4 + 10;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.listArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RecommendModel *model = self.listArr[indexPath.row];
    CreditCardListCell *cell = [CreditCardListCell tempWithTableView:tableView];
    cell.backgroundColor = [UIColor colorWithHexString:@"F41458"];
    [cell.im sd_setImageWithURL:[NSURL URLWithString:model.img]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RecommendModel *model = self.listArr[indexPath.row];
    if (model.link.length <= 0) {
        
        return;
    }
    
    CreditCardDetailViewController *VC = [[CreditCardDetailViewController alloc]init];
    VC.url = model.link;
    [VC setNavBarWithTitle:model.name];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 微信好友分享
- (IBAction)onShareWX:(UIButton *)sender {
    
    [self getShareNoWithFlat:@"微信好友" andSender:sender];
    
}

#pragma mark - 微信朋友圈分享
- (IBAction)onSharePYQ:(UIButton *)sender {
    
    sender.enabled = NO;
    [self getShareNoWithFlat:@"微信朋友圈" andSender:sender];
    
}

#pragma mark - QQ好友分享
- (IBAction)onShareQQ:(UIButton *)sender {
    
    [self getShareNoWithFlat:@"QQ好友" andSender:sender];
}

#pragma mark - QQ空间分享
- (IBAction)onShareKJ:(UIButton *)sender {
    
    [self getShareNoWithFlat:@"QQ空间" andSender:sender];
}

- (void)getShareNoWithFlat:(NSString *)flat andSender:(UIButton *)sender{

    MJWeakSelf
    CreditCardStore *store = [[CreditCardStore alloc] init];
    [store getShareNoWithFlat:flat andShareTo:nil andType:@"1" success:^(NSString *shareNo) {
        
        [weakSelf shareWithFlat:flat andShareNo:shareNo];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            sender.enabled = YES;
        });
        
    } failure:^(NSError *error) {
        
        sender.enabled = YES;
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
    
}

- (void)shareWithFlat:(NSString *)flat andShareNo:(NSString *)shareNo{
    
    NSString *title = [HomeList sharedInstance].recommendModel.name;
    NSString *content = [HomeList sharedInstance].recommendModel.comment;
    NSString *imgUrl = [HomeList sharedInstance].recommendModel.smallImg;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
    UIImage *img = [UIImage imageWithData:data];
    NSString *url = [NSString stringWithFormat:@"%@?shareNo=%@&customId=%@&pId=%@",[HomeList sharedInstance].recommendModel.link,shareNo,[UserDefaultsManager sharedInstance].user_id,[HomeList sharedInstance].recommendModel.uid];
    
    if ([flat isEqualToString:@"微信好友"]) {
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;//主标题
        message.description = content;//描述
        [message setThumbImage:[ImgManager getSimpleImg:img]];
        
        WXWebpageObject *webobject = [WXWebpageObject object];
        webobject.webpageUrl = url;
        message.mediaObject = webobject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.message = message;
        req.scene = WXSceneSession;
        [WXApi sendReq:req];
    }else if ([flat isEqualToString:@"微信朋友圈"]){
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;//主标题
        message.description = content;//描述
        [message setThumbImage:[ImgManager getSimpleImg:img]];
    
        WXWebpageObject *webobject = [WXWebpageObject object];
        webobject.webpageUrl = url;
        message.mediaObject = webobject;
    
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.message = message;
        req.scene = WXSceneTimeline;
        [WXApi sendReq:req];
    }else if ([flat isEqualToString:@"QQ好友"]){
        
        QQApiTextObject *txtObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:url] title:title description:content previewImageURL:[NSURL URLWithString:imgUrl]];
    
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
    
        dispatch_async(dispatch_get_main_queue(), ^{
            [QQApiInterface sendReq:req];
        });
    }else {
        
        QQApiTextObject *txtObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:url] title:title description:content previewImageURL:[NSURL URLWithString:imgUrl]];
    
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
    
        dispatch_async(dispatch_get_main_queue(), ^{
            [QQApiInterface SendReqToQZone:req];
        });
    }

}

#pragma mark - 分享成功回调
- (void)shareSuccessBlock{
    
    [self didBgView];
    [self showMBPError:@"分享成功"];
}

#pragma mark - 点击底部分享按钮
- (void)onFooterViewShareBtn {
    
    [self onRightBtn:nil];
}

@end
